package com.lyf.aspect;

import com.lyf.annotation.AutoFill;
import com.lyf.constant.AutoFillConstant;
import com.lyf.context.BaseContext;
import com.lyf.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Slf4j
@Component
public class AutoFillAspect {

    @Pointcut("execution(* com.lyf.mapper..*.*(..)) && @annotation(com.lyf.annotation.AutoFill)")
    public void autoFillPointCut(){}
    
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {
        log.info("开始进行数据填充");
        // 获取当前被拦截的方法的数据库操作类型
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = methodSignature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();
        // 获取拦截的方法参数
        Object args[] = joinPoint.getArgs();
        if(args == null || args.length == 0){
            return;
        }
        Object entity = args[0];
        // 准备赋值的数据
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();

        try {
            // 根据对应的数据库操作类型，为对应的属性赋值
            if(operationType == OperationType.INSERT){
                invokeMethod(entity, AutoFillConstant.SET_CREATE_TIME, now);
                invokeMethod(entity, AutoFillConstant.SET_UPDATE_TIME, now);
                invokeMethod(entity, AutoFillConstant.SET_CREATE_USER, currentId);
                invokeMethod(entity, AutoFillConstant.SET_UPDATE_USER, currentId);
            }else if(operationType == OperationType.UPDATE){
                invokeMethod(entity, AutoFillConstant.SET_UPDATE_TIME, now);
                invokeMethod(entity, AutoFillConstant.SET_UPDATE_USER, currentId);
            }
        } catch (Exception e) {
            log.error("自动填充字段失败: ", e);
        }

    }

    /**
     * 通过反射调用实体类的setter方法
     * @param entity 实体对象
     * @param methodName 方法名
     * @param value 参数值
     */
    private void invokeMethod(Object entity, String methodName, Object value) {
        Class<?> clazz = entity.getClass();
        try {
            // 获取setter方法
            Method method = clazz.getMethod(methodName, value.getClass());
            // 调用方法
            method.invoke(entity, value);
        } catch (Exception e) {
            log.warn("无法调用方法 {}: {}", methodName, e.getMessage());
        }
    }
}